// import { useWujie } from '@plugins/wujieMicro';

const getWindow = window?.__POWERED_BY_WUJIE__ ? window.parent : window;
// const { parentWindow, selfWindow, window: win, document: _document } = useWujie();
// 设置token
export const setToken = (value: string): void => {
    // value为用户登录后的token值
    if (value.length >= 32) {
        window.localStorage.setItem('KumianmeiToken', value);
    }
};

// 获取token
export const getToken = (): string => {
    return window.localStorage.getItem('KumianmeiToken') || '';
};

/**
 * @function getUserInfo 获取用户信息
 * @author: 邓子强
 * @Date: 2020/12/26
 * @desc 该方法适合用来获取用户登陆之后不变的信息，例如id,性别等，不适合用来获取金钱等动态的信息
 */
export const getUserInfo = <T>(): T | null => {
    try {
        const userInfo = getWindow.localStorage.getItem('userInfo');
        if (userInfo) {
            return JSON.parse(userInfo);
        }
        return null;
    } catch (e) {
        return null;
    }
};

export function getUserId() {
    try {
        const userInfo = getWindow.localStorage.getItem('userInfo');
        if (userInfo) {
            return JSON.parse(userInfo).displayUserId;
        }
        return undefined;
    } catch (e) {
        return undefined;
    }
}

// type ['local','session'] 存入localStorage(默认)或者sessionStorage
const getStorage = (type = 'local') => {
    return type === 'session' ? sessionStorage : localStorage;
};

export const setStorageItem = (key: string, value: string | object, type = 'local'): void => {
    if (typeof value === 'object') {
        getStorage(type).setItem(key, JSON.stringify(value));
    } else {
        getStorage(type).setItem(key, `${value}`);
    }
};
export const getStorageItem = (key: string, type = 'local'): string | object | null => {
    const res = getStorage(type).getItem(key);
    if (!res) {
        return res;
    }
    try {
        return JSON.parse(res);
    } catch (e) {
        return res;
    }
};
export const getStorageItemObject = (key: string, type = 'local'): object | null => {
    return JSON.parse(getStorage(type).getItem(key));
};
export const removeStorageItem = (key: string, type = 'local'): void => {
    getStorage(type).removeItem(key);
};
export const removeAllStorage = (type = 'local'): void => {
    getStorage(type).clear();
};
